// 组织架构
import React, { useState, useEffect } from 'react'
import useStore from '../../components/useStore'
import { Button, Card, Col, Empty, Form, InputNumber, notification, Row, Input, Pagination, Select, TreeSelect, DatePicker } from 'antd'
import { SearchOutlined, FileDoneOutlined, FileExcelOutlined } from '@ant-design/icons'
import dayjs from 'dayjs';
import * as XLSX from 'xlsx'; // 引入xlsx库用于生成Excel
import request from '../../untils/request'

const UpdateOrSearch = () => { // 更新/查看用户
    const { collapsed } = useStore()
    const [roleOptions, setroleOptions] = useState([]) // 用户可选角色
    const [frameworkOptions, setframeworkOptions] = useState([]) // 可选的组织架构
    const [activeTabKey, setactiveTabKey] = useState("tab1")
    const [loading, setLoading] = useState(false) // 导出加载状态
    const tabList = [
        {
            key: 'tab1',
            tab: '用户列表',
        },
        {
            key: 'tab2',
            tab: '用户详情',
        },
    ]
    const [searchFrom] = Form.useForm() // 搜索栏的form对象与用户信息的form对象
    const [userForm] = Form.useForm()
    const [currentPage, setcurrentPage] = useState(1) // 所查看用户的当前页
    const [users, setusers] = useState([]) // 所查看的用户列表
    const [userDetail, setuserDetail] = useState(null) // 所查看的具体用户
    const [total, settotal] = useState(0)
    const userStatusOptioins = [
        { value: 0, label: "正常" },
        { value: 1, label: "休假中" },
        { value: 2, label: "出差中" }
    ]
    const accountStatusOptioins = [
        { value: 0, label: "正常" },
        { value: 1, label: "禁止登入" }
    ]

    // 将数据转换为Excel并下载
    const exportToExcel = (data, filename = '用户列表') => {
        // 定义要导出的字段和对应的表头
        const columns = [
            { key: 'id', title: '用户ID' },
            { key: 'work_number', title: '工号' },
            { key: 'name', title: '姓名' },
            { key: 'account', title: '登录账号' },
            { key: 'phone', title: '手机号码' },
            { key: 'position', title: '职务' },
            { key: 'role_name', title: '角色名称' },
            { key: 'framework_name', title: '所属组织' },
            { key: 'board_date', title: '入职日期' },
            { key: 'birthday', title: '出生日期' },
            { key: 'user_status', title: '用户状态', formatter: (value) => {
                const statusMap = {0: '正常', 1: '休假中', 2: '出差中'};
                return statusMap[value] || '';
            }},
            { key: 'account_status', title: '账号状态', formatter: (value) => {
                const statusMap = {0: '正常', 1: '禁止登入'};
                return statusMap[value] || '';
            }},
            { key: 'create_time', title: '创建时间' },
        ];
        
        // 处理数据，只保留需要导出的字段
        const formattedData = data.map(item => {
            const formattedItem = {};
            columns.forEach(col => {
                // 应用格式化函数（如果有）
                formattedItem[col.title] = col.formatter 
                    ? col.formatter(item[col.key]) 
                    : (item[col.key] || '');
            });
            return formattedItem;
        });
        
        // 创建工作簿和工作表
        const worksheet = XLSX.utils.json_to_sheet(formattedData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '用户数据');
        
        // 下载Excel文件
        XLSX.writeFile(workbook, `${filename}.xlsx`);
    };

    // 导出Excel功能
    const exportExcel = async () => {
        // 显示加载状态
        setLoading(true);
        notification.info({ message: "正在准备导出数据，请稍候..." });
        
        try {
            const condition = await searchFrom.getFieldsValue();
            // 请求所有符合条件的数据（pageSize设为total）
            request("/admin/user/searchUser", {
                method: "POST",
                mode: 'cors',
                body: {
                    condition,
                    pageSize: total, // 使用总条数作为页大小
                    offset: 0 // 从第一条开始
                }
            }).then(result => {
                if (result.code === 200 && result.data && result.data.length > 0) {
                    // 调用导出函数
                    exportToExcel(result.data, '用户列表查询结果');
                    notification.success({ message: `成功导出 ${result.data.length} 条数据` });
                } else {
                    notification.warning({ message: "没有可导出的数据" });
                }
            });
        } catch (error) {
            notification.error({ message: "导出失败，请重试" });
            console.error("导出错误:", error);
        } finally {
            // 隐藏加载状态
            setLoading(false);
        }
    };

    const search = async () => {
        var condition = await searchFrom.getFieldsValue() // 查询的条件
        var req = {
            condition: condition,
            pageSize: 10,
            offset: (currentPage - 1) * 10
        }
        request("/admin/user/searchUser", { // 搜索用户
            method: "POST",
            mode: 'cors',
            body:req
        }).then(data => {
            if (data.code == 200) {
                setusers(data.data)
                settotal(data.total)
                notification.success({
                    message: data.msg
                })
            } else {
                notification.error({
                    message: "未知错误"
                })
            }
        })
    }

    const toDetailUser = async (user_id) => { // 前往用户详情页（切换标签并且查询数据）
        request("/admin/user/getUserInfo", { // 搜索具体用户
            method: "POST",
            mode: 'cors',
            body: {
                user_id: user_id
            }
        }).then(data => {
            if (data.code == 200) {
                data.data = {
                    ...data.data,
                    birthday: data.data.birthday == null ? null : dayjs(data.data.birthday),
                    board_date: data.data.board_date == null ? null : dayjs(data.data.board_date)
                }
                setuserDetail(data.data)
                userForm.setFieldsValue(data.data)
                notification.open({
                    message: data.msg
                })
            } else {
                notification.open({
                    message: "未知错误"
                })
            }
        })
        setactiveTabKey("tab2")
    }

    const changePage = async (e) => { // 切换页面
        setcurrentPage(e)
    }

    const save = async () => { // 保存修改
        var req = await userForm.getFieldsValue()
        req = {
            ...req,
            birthday: req.birthday ? dayjs(req.birthday).format("YYYY-MM-DD") : null,
            board_date: req.board_date ? dayjs(req.board_date).format("YYYY-MM-DD") : null
        }
        if (req.id == 1) {
            notification.open({
                message: "超级管理员不允许修改"
            })
            return
        }
        request("/admin/user/updateUserInfo", { // 更新用户信息
            method: "POST",
            mode: 'cors',
            body: req
        }).then(data => {
            notification.open({
                message: data.msg
            })
        })
    }

    useEffect(() => { // 页面加载时获取角色与组织架构列表
        // 获取角色的可选列表（除超级管理员以外均可分配）
        fetch("/admin/role/getRoleList", {
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(response => {
            return response.json();
        }).then(data => {
            // 假设后端直接返回角色数组，不包含code字段
            if (Array.isArray(data)) {
                // 转换格式并添加超级管理员选项
                const roleList = data.map(role => ({
                    value: role.id,
                    label: role.role_name
                }));
                roleList.push({
                    value: 1,
                    label: "超级管理员",
                    disabled: true
                });
                setroleOptions(roleList);
            } else {
                notification.open({
                    message: "获取角色列表格式不正确"
                });
            }
        }).catch(error => {
            notification.open({
                message: "获取角色列表失败"
            });
            console.error("获取角色列表错误:", error);
        });

        // 获取组织架构的可选列表
        fetch("/admin/framework/getFramework", {
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(response => {
            return response.json();
        }).then(data => {
            // 假设后端直接返回组织架构数组，不包含code字段
            if (Array.isArray(data)) {
                data[0].disabled = true; // 根节点禁止挂载用户
                setframeworkOptions(data);
            } else {
                notification.open({
                    message: "获取组织架构格式不正确"
                });
            }
        }).catch(error => {
            notification.open({
                message: "获取组织架构失败"
            });
            console.error("获取组织架构错误:", error);
        });
    }, []);

    useEffect(() => {
        search()
    }, [currentPage])

    return (
        <div style={{
            height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
            backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                <div style={{
                    fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
                    textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
                }}>
                    <Card 
                        title="请输入用户信息进行查询" 
                        style={{ width: "100%", marginTop: "2vh" }}
                        extra={
                            <Button 
                                icon={<FileExcelOutlined />} 
                                onClick={exportExcel} 
                                loading={loading}
                            >
                                导出Excel
                            </Button>
                        }
                    >
                        <Form style={{ width: "95%" }} form={searchFrom}>
                            <Row gutter={24}>
                                <Col span={12}>
                                    <Form.Item
                                        label="工号"
                                        name="work_number"
                                        rules={[
                                            { required: false, message: '请输入正整数' },
                                            () => ({
                                                validator(_, value) {
                                                    if (value === undefined || value === null) return Promise.resolve()
                                                    if (Number.isInteger(value) && value > 0) {
                                                        return Promise.resolve()
                                                    }
                                                    return Promise.reject(new Error('请输入大于0的整数'))
                                                },
                                            }),
                                        ]}
                                    >
                                        <InputNumber
                                            min={1}
                                            autoComplete="new-password"
                                            precision={0}
                                            maxLength={10}
                                            controls={false}
                                            style={{ width: '100%' }}
                                            placeholder="请输入正整数"
                                            onPaste={(e) => {
                                                const paste = e.clipboardData.getData('text');
                                                if (!/^\d+$/.test(paste)) {
                                                    e.preventDefault();
                                                }
                                            }}
                                            formatter={(value) => `${value}`.replace(/\D/g, '')}
                                            parser={(value) => value?.replace(/\D/g, '')}
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label="id"
                                        name="id"
                                        rules={[
                                            { required: false, message: '请输入正整数' },
                                            () => ({
                                                validator(_, value) {
                                                    if (value === undefined || value === null) return Promise.resolve()
                                                    if (Number.isInteger(value) && value > 0) {
                                                        return Promise.resolve()
                                                    }
                                                    return Promise.reject(new Error('请输入大于0的整数'))
                                                },
                                            }),
                                        ]}
                                    >
                                        <InputNumber
                                            min={1}
                                            autoComplete="new-password"
                                            precision={0}
                                            maxLength={10}
                                            controls={false}
                                            style={{ width: '100%' }}
                                            placeholder="请输入正整数"
                                            onPaste={(e) => {
                                                const paste = e.clipboardData.getData('text');
                                                if (!/^\d+$/.test(paste)) {
                                                    e.preventDefault();
                                                }
                                            }}
                                            formatter={(value) => `${value}`.replace(/\D/g, '')}
                                            parser={(value) => value?.replace(/\D/g, '')}
                                        />
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                        <Button icon={<SearchOutlined />} onClick={search}>搜索</Button>
                    </Card>
                    <Card style={{ width: "100%", marginTop: "2vh" }}
                        tabList={tabList}
                        activeTabKey={activeTabKey}
                        onTabChange={() => { // 切换标签
                            activeTabKey == "tab1" ? setactiveTabKey("tab2") : setactiveTabKey("tab1")
                        }}
                    >
                        <div style={{ display: activeTabKey == "tab1" ? "" : "none" }}>
                            {
                                users.length == 0 ?
                                    (<div>
                                        <Empty />
                                    </div>) :
                                    (<div>
                                        <Row style={{ width: "100%", marginTop: '0.5vh', marginLeft: "0.25vw", backgroundColor: '#156ef3d8', color: 'white' }} gutter={24}>
                                            <Col span={3}>序号</Col>
                                            <Col span={6}>姓名</Col>
                                            <Col span={6}>联系方式</Col>
                                            <Col span={6}>职位</Col>
                                            <Col span={3}>操作</Col>
                                        </Row>
                                        <div style={{
                                            height: "40vh",
                                            overflowY: "auto",
                                            overflowX: "hidden",
                                            paddingRight: "10px"
                                        }}>
                                            {users.map((item, index) => {
                                                const isEvenRow = index % 2 === 0;
                                                return (
                                                    <Row
                                                        key={index}
                                                        style={{
                                                            width: "100%",
                                                            marginTop: "0.5vh",
                                                            marginLeft: "0.25vw",
                                                            borderBottom: "1px solid gray",
                                                            padding: "0.1rem",
                                                            backgroundColor: isEvenRow ? "#f9fafb" : "#ffffff",
                                                            transition: "background-color 0.2s"
                                                        }}
                                                        onMouseEnter={(e) => e.currentTarget.style.backgroundColor = "#f3f4f6"}
                                                        onMouseLeave={(e) => e.currentTarget.style.backgroundColor = isEvenRow ? "#f9fafb" : "#ffffff"}
                                                        gutter={24}
                                                    >
                                                        <Col span={3}>{index + 1}</Col>
                                                        <Col span={6} style={{ whiteSpace: "normal", wordBreak: "break-all" }}>{item.name}</Col>
                                                        <Col span={6} style={{ whiteSpace: "normal", wordBreak: "break-all" }}>{item.phone}</Col>
                                                        <Col span={6} style={{ whiteSpace: "normal", wordBreak: "break-all" }}>{item.position}</Col>
                                                        <Col span={3}>
                                                            <Button
                                                                size='small'
                                                                onClick={() => toDetailUser(item.id)}
                                                                style={{ marginRight: "8px" }}
                                                            >详情</Button>
                                                        </Col>
                                                    </Row>
                                                );
                                            })}
                                        </div>
                                        <Pagination
                                            current={currentPage}
                                            onChange={changePage}
                                            total={total}
                                        />
                                    </div>)
                            }
                        </div>
                        <div style={{ display: activeTabKey == "tab1" ? "none" : "" }}>
                            {
                                userDetail == null ?
                                    (<div>
                                        <Empty description="请选择具体的用户查看信息" />
                                    </div>) :
                                    (<div style={{
                                        padding: '0 16px',
                                        overflowX: 'hidden',
                                        overflowY: "scroll",
                                        height: "45vh",
                                        width: "100%"
                                    }}>
                                        <Form
                                            form={userForm}
                                            labelCol={{ span: 8 }}
                                            wrapperCol={{ span: 16 }}
                                            style={{
                                                maxWidth: '100%',
                                                boxSizing: 'border-box',
                                                width: "95%"
                                            }}
                                        >
                                            {/* 不可修改区域标题 */}
                                            <Row>
                                                <Col span={24}>
                                                    <h3 style={{
                                                        margin: '16px 0',
                                                        color: '#1890ff',
                                                        borderLeft: '3px solid #1890ff',
                                                        paddingLeft: 12
                                                    }}>
                                                        仅展示
                                                    </h3>
                                                </Col>
                                            </Row>

                                            {/* 不可修改区域内容 */}
                                            <Row gutter={24} style={{ marginBottom: '16px' }}>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item name="id" label="id">
                                                        <Input disabled style={{ width: '100%' }} />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item name="work_number" label="工号">
                                                        <Input disabled style={{ width: '100%' }} />
                                                    </Form.Item>
                                                </Col>
                                            </Row>

                                            <Row gutter={24} style={{ marginBottom: '16px' }}>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item name="account" label="登入账号">
                                                        <Input disabled style={{ width: '100%' }} />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={12} xs={24} sm={12} />
                                            </Row>

                                            {/* 可修改区域标题 */}
                                            <Row>
                                                <Col span={24}>
                                                    <h3 style={{
                                                        margin: '16px 0',
                                                        color: '#1890ff',
                                                        borderLeft: '3px solid #1890ff',
                                                        paddingLeft: 12
                                                    }}>
                                                        可修改
                                                    </h3>
                                                </Col>
                                            </Row>

                                            {/* 可修改区域内容 */}
                                            <Row gutter={24} style={{ marginBottom: '16px' }}>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item
                                                        label="姓名"
                                                        name="name"
                                                        rules={[{ required: true, message: '用户姓名不能为空' }]}
                                                    >
                                                        <Input maxLength={20} showCount style={{ width: '100%' }} />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item label="角色" name="role_id">
                                                        <Select
                                                            options={roleOptions}
                                                            placeholder="请选择角色"
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                            </Row>

                                            <Row gutter={24} style={{ marginBottom: '16px' }}>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item label="组织" name="framework_id">
                                                        <TreeSelect
                                                            treeData={frameworkOptions}
                                                            placeholder="请选择组织"
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item
                                                        label="手机号码"
                                                        name="phone"
                                                        rules={[
                                                            () => ({
                                                                validator(_, value) {
                                                                    if (!value) return Promise.resolve();
                                                                    const phoneRegex = /^1[3-9]\d{9}$/;
                                                                    return phoneRegex.test(value)
                                                                        ? Promise.resolve()
                                                                        : Promise.reject(new Error('请输入正确的手机号码'));
                                                                }
                                                            })
                                                        ]}
                                                    >
                                                        <Input
                                                            maxLength={11}
                                                            showCount
                                                            placeholder='请输入手机号码（非必填）'
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                            </Row>

                                            <Row gutter={24} style={{ marginBottom: '16px' }}>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item
                                                        label="职务"
                                                        name="position"
                                                        rules={[{ required: false }]}
                                                    >
                                                        <Input
                                                            maxLength={50}
                                                            showCount
                                                            placeholder='请输入职务'
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item
                                                        label="入职日期"
                                                        name="board_date"
                                                        rules={[{ required: false }]}
                                                    >
                                                        <DatePicker
                                                            placeholder='请选择入职日期'
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                            </Row>

                                            <Row gutter={24} style={{ marginBottom: '16px' }}>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item
                                                        label="出生日期"
                                                        name="birthday"
                                                        rules={[{ required: false }]}
                                                    >
                                                        <DatePicker
                                                            placeholder='请选择出生日期'
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item
                                                        label="用户状态"
                                                        name="user_status"
                                                        rules={[{ required: false }]}
                                                    >
                                                        <Select
                                                            options={userStatusOptioins}
                                                            placeholder="请选择用户状态"
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                            </Row>

                                            <Row gutter={24} style={{ marginBottom: '16px' }}>
                                                <Col span={12} xs={24} sm={12}>
                                                    <Form.Item
                                                        label="账号状态"
                                                        name="account_status"
                                                        rules={[{ required: false }]}
                                                    >
                                                        <Select
                                                            options={accountStatusOptioins}
                                                            placeholder="请选择账号状态"
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={12} xs={24} sm={12} />
                                            </Row>

                                            {/* 保存按钮 */}
                                            <Row>
                                                <Col span={24} style={{ textAlign: 'right', marginBottom: '16px' }}>
                                                    <Button
                                                        icon={<FileDoneOutlined />}
                                                        type="primary"
                                                        onClick={save}
                                                    >
                                                        保存
                                                    </Button>
                                                </Col>
                                            </Row>
                                        </Form>
                                    </div>)
                            }
                        </div>
                    </Card>
                </div>
            </div>
        </div>
    )
}

export default UpdateOrSearch

var styles = {
    kshcontainer: {
        width: "98%",
        height: "95%",
        position: "absolute", top: "3%",
        left: "1%", backgroundColor: "white",
        color: "black",
        borderRadius: "10px",
    },
}
    